package com.eastidea.live.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.eastidea.live.util.Constant;
import com.eastidea.live.util.FileUtil;
import com.eastidea.live.util.RequestObserver;

public class SingleFileUploader extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestObserver.observe(request);
		PrintWriter writer = response.getWriter();
		
//		AppService appService = (AppService) WebApplicationContextUtils
//				.getWebApplicationContext(request.getSession().getServletContext())
//				.getBean("appServiceImpl");

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(10240000);

			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(10002400000l);
			upload.setSizeMax(10002400000l);
			upload.setHeaderEncoding("UTF-8");

			String sn = "";
			String category = "";
			FileItem fileItem = null;

			List<?> items = upload.parseRequest(request);

			for (int i = 0; i < items.size(); i++) {
				FileItem item = (FileItem) items.get(i);
				if (!item.isFormField() && item.getName().length() > 0) {
					fileItem = item;
				} else if (item.isFormField()
						&& item.getFieldName().equals("category")) {
					category = item.getString();
				} else if (item.isFormField()
						&& item.getFieldName().equals("sn")) {
					sn = item.getString();
				}
			}
			String dateString = new SimpleDateFormat("yyMMdd")
					.format(new Date());
			String folderRelativePath = Constant.PATH_UPLOAD + "/" + category
					+ "/" + dateString + "/";
			String baseFolder = this.getServletConfig().getServletContext()
					.getRealPath("/").replace("\\", "/");

			String folderAbsolutePath = baseFolder + folderRelativePath;
			String fullAbsolutePath = "";
			String fullRelativePath = "";

			File folder = new File(folderAbsolutePath);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			if (fileItem == null) {
				writer.print("{code:'-1', sn:'" + sn + "', filePath:'" + fullRelativePath
						+ "'}");
				return;
			}
			String extName = FileUtil.getExtension(fileItem.getName(), "jpg");
			String fileName = new DecimalFormat("00000000").format(Math
					.random() * 100000000) + "." + extName;

			fullAbsolutePath = folderAbsolutePath + fileName;
			fullRelativePath = folderRelativePath + fileName;
			File file = new File(fullAbsolutePath);
			if (file.exists()) {
				file.delete();
			}
			fileItem.write(new File(fullAbsolutePath));

			response.setStatus(response.SC_OK);
			writer.print("{code:'0', sn:'" + sn + "', filePath:'" + fullRelativePath
					+ "'}");

			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
			writer.print("{}");
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}
